package com.example.blog.service.Impl;

import com.example.blog.config.redis.RedisConstant;
import com.example.blog.entity.User;
import com.example.blog.entity.UserDTO;
import com.example.blog.mapper.UserMapper;
import com.example.blog.service.UserService;
import com.example.blog.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 *
 * @Author: lu
 * @Date: 2023-09-05-8:54
 * @Description: 业务实现层
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    UserDTO userDTO;

    @Override
    public List<User> findAll() {
        //List<User> userList = userMapper.findAll();
        //return userList;

        List<User> userList = (List<User>) redisUtil.get(RedisConstant.ALL_USER_KEY);
        if(CollectionUtils.isEmpty(userList)){
            userList = userMapper.findAll();
            //加入redis缓存
            redisUtil.set(RedisConstant.ALL_USER_KEY,userList);
            //System.out.println(redisUtil.get(RedisConstant.ALL_USER_KEY));
        }
        return userList;

    }

    @Override
    public UserDTO find() {
        List<User> all = userMapper.findAll();
        userDTO.setUsers(all);
        userDTO.setCount(all.size());

        for (int i = all.size() -1; i >= 0; i--) {
            if ("12345".equals(all.get(i).getPassWord()) ) {
                userDTO.setName(all.get(i).getUserName());
            }
        }
        return userDTO;
    }

    @Override
    public void createUser(User user) {
        //redisUtil.del(RedisConstant.ALL_USER_KEY);

        userMapper.insert(user);

    }

    @Override
    public void updateUser(User user) {
        //删除缓存
        redisUtil.del(RedisConstant.ALL_USER_KEY);

        userMapper.update(user);


    }

    @Override
    public void deleteUser(int id) {
        userMapper.delete(id);

    }

    @Override
    public List<User> login(User user) {
        //List<User> userLogin = (List<User>) redisUtil.get(RedisConstant.ALL_USER_KEY);
        //if(CollectionUtils.isEmpty(userLogin)){
        //    userLogin = userMapper.login(user);
        //    redisUtil.set(RedisConstant.ALL_USER_KEY,userLogin);
        //}
        //return  userLogin;

        List<User> login = userMapper.login(user);
        return login;
    }


    @Override
    public User login1(User user) {
        User u = userMapper.login1(user);
        if (null != u) {
            return u;
        }
        throw new RuntimeException("认证失败");
    }

}
